import { EllipsisOutlined } from '@ant-design/icons';
import { Col, Dropdown, Menu, Row, Card } from 'antd';
import React, { Component, Suspense } from 'react';

import { Dispatch } from 'redux';
import { GridContent } from '@ant-design/pro-layout';
import { RadioChangeEvent } from 'antd/es/radio';
import { RangePickerValue } from 'antd/es/date-picker/interface';
import { connect } from 'dva';
import PageLoading from './components/PageLoading';
import { getTimeDistance } from './utils/utils';
import { AnalysisData } from './data';
import styles from './style.less';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/line';
import 'echarts/lib/chart/pie';
import 'echarts/lib/chart/bar';
import 'echarts/lib/chart/gauge';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/lib/component/legend';
import { max } from 'moment';

const Monitor = require('./monitor.js')

const IntroduceRow = React.lazy(() => import('./components/IntroduceRow'));
const SalesCard = React.lazy(() => import('./components/SalesCard'));
const TopSearch = React.lazy(() => import('./components/TopSearch'));
const ProportionSales = React.lazy(() => import('./components/ProportionSales'));
const OfflineData = React.lazy(() => import('./components/OfflineData'));

interface AnalysisProps {
  dashboardAndanalysis: any;
  dispatch: Dispatch<any>;
  loading: boolean;
}

interface AnalysisState {
  salesType: 'all' | 'online' | 'stores';
  currentTabKey: string;
  rangePickerValue: RangePickerValue;
  a01Data: any;
  a02Data: any;
  a03Data: any;
  a14Data: any;
  a04Data: any;
}

class Analysis extends Component<AnalysisProps, AnalysisState> {
  state: AnalysisState = {
    salesType: 'all',
    currentTabKey: '',
    rangePickerValue: getTimeDistance('year'),
    a01Data: [],
    a02Data: {},
    a03Data: [],
    a14Data: [],
    a04Data: {}
  };

  reqRef: number = 0;

  timeoutId: number = 0;

  componentDidMount() {
    const that = this;
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'dashboardAndanalysis/fetch',
        callback: this.initContainerOne,
      });
    });

    const url = "ws://114.215.44.80:8081/topics";
    const topicDomain = "demo";
    Monitor.subscribeTopic(url, topicDomain, [
      {
        id: "a01", 
        on_event: function(events:any) {
          console.log('a01 监控数据描述 events-->', events);   
          that.setState({
            a01Data: events
          })
        }
      },
      {
        id: "a14", 
        on_event: function(events:any) {
          console.log('a14 监控数据描述 events-->', events); 
          that.setState({
            a14Data: events
          })  
        }
      },
      {
        id: "a03", 
        on_event: function(events:any) {
          console.log('a03 监控数据描述 events-->', events);   
          that.setState({
            a03Data: events
          })
        }
      },
      {
        id: "a02", 
        on_event: function(events:any) {
          console.log('a02 监控数据描述 events-->', events);   
          that.setState({
            a02Data: events
          })
        }
      },
      {
        id: "a04", 
        on_event: function(events:any) {
          console.log('a04 监控数据描述 events-->', events);   
          that.setState({
            a04Data: events
          })
        }
      },
    ]);	
  }

  // @ts-ignore
  initContainerOne = () => {
    const { list } = this.props.dashboardAndanalysis;
    const { a02Data } = this.state;
    // const {ratio,total_series_data,phone_status,phone_count,group} = list;
    // @ts-ignore
    let option =  {
      title: {
        text: '当日电话量占比分布'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      series: [
        {
            name: '访问来源',
            type: 'pie',
            selectedMode: 'single',
            radius: [0, '30%'],

            label: {
                position: 'inner'
            },
            labelLine: {
                show: false
            },
            // data: list?.ratio?.series_data || []
            data: [
                {value: a02Data.n_acc_trunks_ib, name: '呼入量', selected: true},
                {value: a02Data.n_acc_trunks_ob, name: '呼出量'},
            ]
        },
        {
            // name: '访问来源',
            type: 'pie',
            radius: ['40%', '55%'],
            label: {
                formatter: ' {b|{b}：}{c} \n {per|{d}%}  ',
                rich: {
                    a: {
                        color: '#999',
                        lineHeight: 22,
                        align: 'center'
                    },
                    hr: {
                        borderColor: '#aaa',
                        width: '100%',
                        borderWidth: 0.5,
                        height: 0
                    },
                    b: {
                        fontSize: 14,
                        lineHeight: 33
                    },
                    per: {
                        color: '#eee',
                        backgroundColor: '#334455',
                        padding: [2, 4],
                        borderRadius: 2
                    }
                }
            },
            // data: list?.ratio?.series_other_data || []
            data: [
                {value: a02Data.n_acc_trunks_ob_ans || 0, name: '呼出接通'},
                {value: a02Data.n_acc_trunks_ob || 0 - a02Data.n_acc_trunks_ob_ans || 0, name: '呼出未接'},
                {value: a02Data.n_acc_trunks_ob_ans || 0, name: '呼入未接'},
                {value: a02Data.n_acc_trunks_ob_ans || 0, name: '呼入接通'}
            ]
        }
      ]
    };

    let option2 = {
      title: {
        text: '当日电话总量统计'
      },
      tooltip: {
          formatter: '{b} : {c}'
      },
      toolbox: {
          feature: {
              restore: {},
              saveAsImage: {}
          }
      },
      series: [
          {
              name: '业务指标',
              type: 'gauge',
              detail: {formatter: '{value}'},
              data: list?.total_series_data || [],
              // data: [{value: 210, name: '总量'}],
              max: list?.total_series_data[0].value + 100,
          }
      ]
    };

    let option3 = {
      title: {
        text: '话务状态实时统计'
      },
      color: ['#3398DB'],
      tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
              type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
      },
      grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
      },
      xAxis: [
          {
              type: 'category',
              data: list?.phone_status?.xAxis_data || [],
              // data: ['空闲', '忙碌', '通话', '整理', '小休', '锁定', '外呼'],
              axisTick: {
                  alignWithLabel: true
              }
          }
      ],
      yAxis: [
          {
              type: 'value'
          }
      ],
      series: [
          {
              name: '数量',
              type: 'bar',
              barWidth: '60%',
              data: list?.phone_status?.series_data || [],
              // data: [10, 52, 200, 334, 390, 330, 220]
          }
      ]
    };

    let option4 = {
      title: {
        text: '话务量趋势图'
      },
      color: ['#3398DB'],
      tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
              type: 'line'        // 默认为直线，可选为：'line' | 'shadow'
          }
      },
      xAxis: {
          type: 'category',
          data: list?.phone_count?.xAxis_data || []
          // data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
          type: 'value'
      },
      series: [{
          name: '当日总量',
          data: list?.phone_count?.series_data || [],
          // data: [820, 932, 901, 934, 1290, 1330, 1320],
          type: 'line'
      }]
    };

    let option5 = {
      title: {
          text: '当日话务量分组统计',
      },
      tooltip: {
          trigger: 'axis',
          axisPointer: {
              type: 'shadow'
          }
      },
      grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
      },
      xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01]
      },
      yAxis: {
          type: 'category',
          data: list?.group?.xAxis_data || [],
          // data: ['销售一组', '销售二组', '销售三组', '销售四组', '销售五组']
      },
      series: [
          {
              name: '当日总量',
              type: 'bar',
              data: list?.group?.series_data || [],
              // data: [18203, 29034, 104970, 131744, 630230]
          },
      ]
    };
  
    // @ts-nocheck
    var myChart = echarts.init(document.getElementById("containerOne"));
    var myChart2 = echarts.init(document.getElementById("containerTwo"));
    var myChart3 = echarts.init(document.getElementById("containerThree"));
    var myChart4 = echarts.init(document.getElementById("containerFour"));
    var myChart5 = echarts.init(document.getElementById("containerFive"));
    myChart.setOption(option);
    myChart2.setOption(option2);
    myChart3.setOption(option3);
    myChart4.setOption(option4);
    myChart5.setOption(option5);

  }

  render() {
    const { dashboardAndanalysis, loading } = this.props;
    const {
      list,
    } = dashboardAndanalysis;

    const { a02Data, a04Data } = this.state;
    

    console.log('dashboardAndanalysis-->',dashboardAndanalysis)

    return (
      <GridContent>
        <React.Fragment>

          <Suspense fallback={<PageLoading />}>
            <IntroduceRow loading={loading} visitData={
              {
                line_up: list?.line_up || '', 
                sign_in: list?.sign_in || '',
                inbound: list?.inbound || '',
                run_off: list?.run_off || '',
                n_acc_trunks_ib: a02Data.n_acc_trunks_ib || 0, // 当日呼入数
                n_queued: a02Data.n_queued || 0, // 实时排队量
                n_login: a04Data.n_login || 0, // 签入坐席量
              }
            } />
          </Suspense>

          <Card>
          <Row
            gutter={24}
            type="flex"
            style={{
              // marginTop: 24,
            }}
          >
            <Col xl={12} lg={24} md={24} sm={24} xs={24}>
              <Suspense fallback={null}>
                <div id="containerOne" style={{width: '100%', height: 300}}></div>
              </Suspense>
            </Col>
            <Col xl={12} lg={24} md={24} sm={24} xs={24}>
              <Suspense fallback={null}>
                <div id="containerTwo" style={{width: '100%', height: 300}}></div>
              </Suspense>
            </Col>
          </Row>
          </Card>

          <Card style={{
              marginTop: 24,
            }}>
          <Row
            gutter={24}
            type="flex"
          >
            <Col xl={12} lg={24} md={24} sm={24} xs={24}>
              <Suspense fallback={null}>
                <div id="containerThree" style={{width: '100%', height: 300}}></div>
              </Suspense>
            </Col>
            <Col xl={12} lg={24} md={24} sm={24} xs={24}>
              <Suspense fallback={null}>
                <div id="containerFour" style={{width: '100%', height: 300}}></div>
              </Suspense>
            </Col>
          </Row>
          </Card>
          <Card style={{
              marginTop: 24,
            }}>
            <div id="containerFive" style={{width: '100%', height: 300}}></div>
          </Card>
        </React.Fragment>
      </GridContent>
    );
  }
}

export default connect(
  ({
    dashboardAndanalysis,
    loading,
  }: {
    dashboardAndanalysis: any;
    loading: {
      effects: { [key: string]: boolean };
    };
  }) => ({
    dashboardAndanalysis,
    loading: loading.effects['dashboardAndanalysis/fetch'],
  }),
)(Analysis);
